import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Toast } from 'vant'
const request = axios.create({
  baseURL: 'http://toutiao.itheima.net'
})
request.interceptors.request.use(
  config => {
    if (store.state.tokenobj.token) {
      config.headers.Authorization = 'Bearer ' + store.state.tokenobj.token
    }
    return config
  },
  err => {}
)

request.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    return response
  },
  async function (error) {
    // 对响应错误做点什么
    console.dir(error)
    try {
      if (error.response.status === 401) {
        let res = await axios({
          url: 'http://toutiao.itheima.net/v1_0/authorizations',
          method: 'put',
          headers: {
            Authorization: 'Bearer ' + store.state.tokenobj.refresh_token
          }
        })
        store.commit('changetoken', {
          token: res.data.data.token,
          refresh_token: store.state.tokenobj.refresh_token
        })
        return request(error.config)
      }
    } catch {
      Toast.fail('你的登录状态失效请重新登录')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default request
